package com.cinema.filter;

import com.cinema.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录验证过滤器
 */
public class LoginFilter implements Filter {

    // 不需要登录验证的URL列表
    private static final List<String> EXCLUDE_URLS = Arrays.asList(
        "/login",
        "/register",
        "/logout",
        "/",
        "/index.jsp",
        "/images/",
        "/css/",
        "/js/",
        "/error/",
        "/WEB-INF/"
    );

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String requestURI = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();

        // 移除上下文路径，获取相对路径
        String relativePath = requestURI.substring(contextPath.length());

        // 检查是否是不需要登录验证的URL
        if (isExcludeUrl(relativePath)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        HttpSession session = httpRequest.getSession(false);
        User user = null;
        if (session != null) {
            user = (User) session.getAttribute("user");
        }

        if (user == null) {
            // 用户未登录，重定向到登录页面
            String loginUrl = contextPath + "/login";

            // 如果是AJAX请求，返回JSON响应
            String requestedWith = httpRequest.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestedWith)) {
                httpResponse.setContentType("application/json");
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.getWriter().write("{\"success\": false, \"message\": \"请先登录\", \"redirect\": \"" + loginUrl + "\"}");
                return;
            }

            // 保存原始请求URL，登录后可以跳转回来
            String originalUrl = requestURI;
            String queryString = httpRequest.getQueryString();
            if (queryString != null) {
                originalUrl += "?" + queryString;
            }
            session = httpRequest.getSession(true);
            session.setAttribute("originalUrl", originalUrl);

            httpResponse.sendRedirect(loginUrl);
            return;
        }

        // 用户已登录，继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理操作
    }

    /**
     * 检查URL是否在排除列表中
     */
    private boolean isExcludeUrl(String url) {
        for (String excludeUrl : EXCLUDE_URLS) {
            if (url.startsWith(excludeUrl)) {
                return true;
            }
        }
        return false;
    }
}
